package com.qf.xiaomi.web.servlet;

import com.qf.xiaomi.pojo.TbAddress;
import com.qf.xiaomi.pojo.TbUser;
import com.qf.xiaomi.service.AddressService;
import com.qf.xiaomi.service.impl.AddressServiceImpl;
import com.qf.xiaomi.utils.StringConstans;
import com.qf.xiaomi.utils.StringUtils;
import com.qf.xiaomi.web.base.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/address")
public class AdressServlet extends BaseServlet {
    AddressService service=new AddressServiceImpl();
    public String add(HttpServletRequest req, HttpServletResponse resp){
        String aname = req.getParameter("aname");
        String aphone = req.getParameter("aphone");
        String adetail = req.getParameter("adetail");
        TbUser user = (TbUser) req.getSession().getAttribute("user");
        long uid = user.getId();

        TbAddress tbAddress = new TbAddress();
        tbAddress.setName(aname);
        tbAddress.setPhone(aphone);
        tbAddress.setDetail(adetail);
        tbAddress.setUid(uid);
        service.addAddress(tbAddress);
        return StringConstans.REDIRECT+"/userservlet?method=getAddress";
    }
    public String setDefault(HttpServletRequest req, HttpServletResponse resp) {
        String aidStr = req.getParameter("aid");
        long aid = Long.parseLong(aidStr);
        TbAddress tbAddress = new TbAddress();
        tbAddress.setId(aid);
        tbAddress.setLevel(1);
        service.setDefault(tbAddress);
        return StringConstans.REDIRECT+"/userservlet?method=getAddress";
    }
    public String delete(HttpServletRequest req, HttpServletResponse resp) {
        String aidStr = req.getParameter("aid");

        if (StringUtils.isEmpty(aidStr)){
            return StringConstans.FORWARD+"/error/error.jsp";
        }
        long aid = Long.parseLong(aidStr);
        int i = service.deleteById(aid);
        System.out.println(i);
        return StringConstans.REDIRECT+"/userservlet?method=getAddress";
    }
    public String update(HttpServletRequest req, HttpServletResponse resp) {
        String aidStr = req.getParameter("aid");
        long aid = Long.parseLong(aidStr);
        String astate = req.getParameter("astate");
        long level = Long.parseLong(astate);
        String aname = req.getParameter("aname");
        String aphone = req.getParameter("aphone");
        String adetail = req.getParameter("adetail");
        TbUser user = (TbUser) req.getSession().getAttribute("user");
        long uid = user.getId();
        TbAddress tbAddress = new TbAddress();
        tbAddress.setId(aid);
        tbAddress.setName(aname);
        tbAddress.setPhone(aphone);
        tbAddress.setDetail(adetail);
        tbAddress.setUid(uid);
        service.updateAdress(tbAddress);
        return StringConstans.REDIRECT+"/userservlet?method=getAddress";
    }
}
